import navToNext from '../../wxjs/navToNext.js'
import xhx_images from '../../xhx_images.js'
import xhx_route from '../../xhx_route.js'

const app = getApp();

let methods = {
  imgLoad, //图片加载处理（瀑布流）
  clickPraise, //点赞
};

var component = {
  properties: {
    tabId: null,
    lists: {
      type: null,
      observer: function (newVal, oldVal) {
        this.imgLoad(newVal);
      }
    }
  },
  data: {
    xhx_images: xhx_images,
    xhx_route: xhx_route,
    leftLists: [],
    rightLists: [],
    timeMsec: (new Date()).getTime()
  },
  methods: Object.assign(navToNext, methods)
};

Component(component);


function imgLoad(lists) {
  const that = this;
  var leftLists = [],
    rightLists = [],
    leftHeights = 0,
    rightHeights = 0;
  for (var i = 0; i < lists.length; i++) {

    try {
      lists[i].releaseVideo = JSON.parse(lists[i].releaseVideo);
    } catch (e) {
      lists[i].releaseVideo = {};
    }
    try {
      lists[i].releaseCover = JSON.parse(lists[i].releaseCover);
    } catch (e) {
      lists[i].releaseCover = {};
    }

    lists[i].height = (350 - 24) / lists[i].releaseCover.width * lists[i].releaseCover.height;

    if (lists[i].height > 500) lists[i].height = 500;

    if (leftHeights <= rightHeights) {
      leftHeights += lists[i].height;
      //左侧
      leftLists.push(lists[i]);
    } else {
      rightHeights += lists[i].height;
      //右侧
      rightLists.push(lists[i]);
    }
  }

  that.setData({
    totalLists: [leftLists, rightLists]
  })
}

function clickPraise(event) {
  const that = this;
  const index = event.currentTarget.dataset.index;
  const idx = event.currentTarget.dataset.idx;
  var totalLists = that.data.totalLists;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  var reqData = {
    trendsId: totalLists[index][idx].uuid,
  };
  var serAddr = app.serAddrs.comfirmLike;

  if (totalLists[index][idx].likesStatus == 1) {
    serAddr = app.serAddrs.cancelLike;
  }

  app.middleware.requestAjax({
    serAddr: serAddr,
    data: reqData,
    success: function(res) {
      if (totalLists[index][idx].likesStatus == 1) {
        totalLists[index][idx].likesStatus = 0;
        totalLists[index][idx].likesCount--;
      } else {
        totalLists[index][idx].likesStatus = 1;
        totalLists[index][idx].likesCount++;
      }
      that.setData({
        totalLists
      })
    },
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "操作失败");
    }
  })
}